<template>
  <div class="menu-add-edit">
    <a-form
      name="advanced_search"
      autoComplete="off"
      class="menu-form"
      :model="formState"
      ref="menuAddFrom"
    >
      <a-form-item
        :name="['name', 'value']"
        :label="formState.name.label"
        :rules="[formState.name.rule]"
      >
        <a-input
          v-model:value="formState.name.value"
          :placeholder="formState.name.placeholder"
          show-count
          :maxlength="20"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        class="tag-item"
        :name="['headImage', 'value']"
        :label="formState.headImage.label"
        :rules="[formState.headImage.rule]"
      >
        <a-input
          v-model:value="formState.headImage.value"
          readonly
          ref="inpTags"
          style="width: 0; height: 0; border: none; background: transparent"
        />
        <a-form-item-rest>
          <upload
            style="margin-top: -12px"
            :fileList="fileList"
            :isAutoUpload="true"
            @uploadFinished="uploadFinished"
            @upload_remove_Finished="upload_remove_Finished"
            :maxCount="1"
            :title="'上传图标'"
          >
          </upload>
        </a-form-item-rest>
        <div style="font-size: 12px">
          图片上传格式大小可以在<a @click="router.push('/config/siteManage')"
            >站点列表</a
          >中的 [编辑]- [扩展设置] 中调整
        </div>
      </a-form-item>
      <a-form-item
        class="menus-item"
        :name="['accessPath', 'value']"
        :label="formState.accessPath.label"
        :rules="[formState.accessPath.rule]"
      >
        <a-input
          @keyup="
            formState.accessPath.value = formState.accessPath.value.replace(
              /[^a-zA-Z0-9]/g,
              ''
            )
          "
          v-model:value="formState.accessPath.value"
          :placeholder="formState.accessPath.placeholder"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        :name="['keyword', 'value']"
        :label="formState.keyword.label"
        :rules="[formState.keyword.rule]"
      >
        <a-input
          v-model:value="formState.keyword.value"
          :placeholder="formState.keyword.placeholder"
          show-count
          :maxlength="20"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        :name="['topicDesc', 'value']"
        :label="formState.topicDesc.label"
        :rules="[formState.topicDesc.rule]"
      >
        <a-textarea
          v-model:value="formState.topicDesc.value"
          :placeholder="formState.topicDesc.placeholder"
          show-count
          :maxlength="100"
          allow-clear
          :rows="5"
        />
      </a-form-item>
      <a-form-item
        class="menus-item"
        :name="['pcTpl', 'value']"
        :label="formState.pcTpl.label"
        :rules="[formState.pcTpl.rule]"
      >
        <div class="pcSelect">
          <a-select
            v-model:value="formState.pcTpl.value"
            @change="changeType"
            placeholder="请选择"
            :options="pcTempList"
          ></a-select>
          <!-- <a class="editor" @click="uploadEditor">编辑</a> -->
        </div>
      </a-form-item>
      <a-form-item
        class="menus-item"
        :name="['mobileTpl', 'value']"
        :label="formState.mobileTpl.label"
        :rules="[formState.mobileTpl.rule]"
      >
        <a-select
          v-model:value="formState.mobileTpl.value"
          @change="changeType2"
          placeholder="请选择"
          :options="phoneTempList"
        ></a-select>
      </a-form-item>
    </a-form>
  </div>
  <div class="saveBtn" :style="styleWidth">
    <a-button type="primary" @click="saveSetting" style="margin-right: 8px">
      保存
    </a-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, onBeforeUnmount, createVNode } from "vue";
import upload from "@/components/upload/uploadFile.vue";
import { message, Modal } from "ant-design-vue";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import { useRoute, useRouter } from "vue-router";
import request from "@/api/index";
import { checkuserManage } from "./formRuler";

interface dataSourceType {
  [propName: string]: any;
}

//data
const isVisible = ref<boolean>(false);
const inpTags = ref<any>(null);
const route: any = useRoute();
const router: any = useRouter();
const fileList = ref<any>([]);
const menuAddFrom = ref<any>("menuAddFrom");
const menuType = ref<number>(1);
const pcTempList = ref<any[]>([]);
const pcTplCopy = ref<any>();

const phoneTempList = ref<any[]>([]);
const formState = reactive<dataSourceType>({
  name: {
    value: "",
    placeholder: "请输入专题名称",
    rule: {
      required: true,
      validator: checkuserManage,
      trigger: ["blur"],
      msg1: "专题名称不能为空！",
      msg2: "专题名称已存在！",
      api: "topicUniqueName",
      params: { id: route.query.id ? route.query.id : null },
    },
    label: "专题名称",
  },
  headImage: {
    value: null,
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "标题图片不能为空！",
    },
    label: "标题图片",
  },
  accessPath: {
    value: "",
    placeholder: "访问路径仅限输入字母、数字",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "访问路径不能为空！",
    },
    label: "访问路径",
  },

  keyword: {
    value: "",
    placeholder: "请输入专题关键字",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "专题关键字不能为空！",
    },
    label: "专题关键字",
  },
  topicDesc: {
    value: "",
    placeholder: "请输入专题描述",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "专题描述不能为空！",
    },
    label: "专题描述",
  },
  pcTpl: {
    value: null,
    rule: {
      required: false,
      trigger: ["blur"],
      message: "PC端模版不能为空！",
    },
    label: "PC端模版",
  },
  mobileTpl: {
    value: null,
    rule: {
      required: false,
      trigger: ["blur"],
      message: "移动端模版不能为空！",
    },
    label: "移动端模版",
  },
  id: "",
});
//method
const changeType = (e: string, options: any) => {
  formState.pcTpl.value = e;
  menuType.value = options.type;
};
const changeType2 = (e: string, options: any) => {
  formState.mobileTpl.value = e;
  menuType.value = options.type;
};
// 详情
const getDetail = async () => {
  if (route.query.type === "add") {
  } else {
    const data = await request.topicDetail({ id: route.query.id });
    formState.name.value = data.name;
    formState.headImage.value = data.headImage;
    fileList.value[0] = data.headImage;
    formState.accessPath.value = data.accessPath;
    formState.keyword.value = data.keyword;
    formState.topicDesc.value = data.topicDesc;
    formState.pcTpl.value = data?.pcTplDto?.tplPath;
    pcTplCopy.value = data?.pcTplDto?.tplPath;
    formState.mobileTpl.value = data?.mobileTplDto?.tplPath;
  }
};

// 上传图片返回值
const uploadFinished = (data: any) => {
  fileList.value = data;
  formState.headImage.value = true;
  nextTick(() => {
    inpTags.value.focus();
    inpTags.value.blur();
  });
};
// 清除图片
const upload_remove_Finished = (data: any) => {
  fileList.value = [];
  formState.headImage.value = null;
  nextTick(() => {
    inpTags.value.focus();
    inpTags.value.blur();
  });
};

// 专题模版选择下拉列表
const getTempList = () => {
  getPcTempList();
  getPhoneTempList();
};
const getPcTempList = async () => {
  const data = await request.topicTplTempList({ type: 1 });
  const arr: any = [];
  console.log(data);
  if (data) {
    data.forEach((item: any) => {
      arr.push({
        label: `${item.tplName} ${item?.tplLabels[0] || ""}、${
          item?.tplLabels[1] || ""
        }`,
        value: item.tplPath,
      });
    });
  }
  pcTempList.value = arr;
};
const getPhoneTempList = async () => {
  const data = await request.topicTplTempList({ type: 2 });
  const arr: any = [];
  console.log(data);
  if (data) {
    data.forEach((item: any) => {
      arr.push({
        label: `${item.tplName} ${item?.tplLabels[0] || ""}、${
          item?.tplLabels[1] || ""
        }`,
        value: item.tplPath,
      });
    });
  }
  phoneTempList.value = arr;
};

// 编辑器编辑
// const uploadEditor = () => {
//   if (formState.pcTpl.value !== pcTplCopy.value)
//     return message.error("请选择当前专题绑定的模版进行编辑！");
//   const relativePathList: any[] = [];
//   relativePathList.push(formState.pcTpl.value);
//   sessionStorage.setItem("relativePaths", JSON.stringify(relativePathList));
//   console.log(
//     JSON.parse(sessionStorage.relativePaths),
//     "sessionStorage.relativePaths"
//   );
//   isVisible.value = true;
// };

//保存 新添或编辑菜单调取接口
const saveSetting = async (msg: dataSourceType) => {
  inpTags.value.focus();
  inpTags.value.blur();
  menuAddFrom.value
    .validate()
    .then(() => {
      const params = {
        name: formState.name.value,
        headImage: { id: fileList.value[0].id, url: fileList.value[0].url },
        id: route.query.id,
        accessPath: formState.accessPath.value,
        keyword: formState.keyword.value,
        topicDesc: formState.topicDesc.value,
        pcTplDto: formState.pcTpl.value
          ? {
              tplPath: formState.pcTpl.value,
            }
          : undefined,
        mobileTplDto: formState.mobileTpl.value
          ? {
              tplPath: formState.mobileTpl.value,
            }
          : undefined,
      };
      request[route.query.type === "edit" ? "topicUpdate" : "topicAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            router.back();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//取消返回
const cancle = () => {
  router.back();
};

onMounted(() => {
  getDetail();
  getTempList();
  useFixeWidth();
});
</script>

<style lang="less" scoped>
.menu-add-edit {
  display: flex;
  flex-direction: row;
  padding: 48px 24px;
  background: #ffffff;
  height: calc(100% - 120px);
  display: flex;
  justify-content: center;
  overflow-y: auto;
}
.pcSelect {
  display: flex;
  align-items: center;
  .editor {
    width: 30px;
    position: absolute;
    left: 375px;
  }
}
.saveBtn {
  position: fixed;
  bottom: 0;
  height: 48px;
  background-color: #fff;
  box-shadow: 0px -12px 48px 16px rgba(0, 0, 0, 0.03),
    0px -9px 28px 0px rgba(0, 0, 0, 0.05),
    0px -6px 16px -8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.closeAll {
  margin-top: 16px;
  width: 120px;
}

.header-content {
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  margin-bottom: 16px;
  padding: 16px;

  .searchContent {
    margin-top: 16px;
  }
}

.selctapi-list {
  margin-top: 8px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.baseTable {
  position: relative;
}

.baseTable .aTable {
  max-height: 450px;
  height: fit-content;
  overflow: auto;
}

::v-deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 60%;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 96px;
    text-align: right;
  }
}

::v-deep(.ant-form-item:last-child) {
  padding-bottom: 24px;
}
</style>
